package io.kimmking.javacourse.mq.activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class ActivemqQueueTest {
//	private static final String url="tcp://192.168.248.129:61616";
	private static final String url="tcp://localhost:61617";
	private static final String qname="tcp-queue";
	
	public static void main(String[]args) throws JMSException, InterruptedException {
		ConnectionFactory cf = new ActiveMQConnectionFactory(url);
		Connection c = cf.createConnection();
		c.start();
		Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Destination d = s.createQueue(qname);
		
		
		MessageConsumer consumer = s.createConsumer(d);
		consumer.setMessageListener(new MessageListener() {

			@Override
			public void onMessage(Message message) {
				TextMessage tm = (TextMessage) message;
				try {
					System.out.println("MessageConsumer1-"+tm.getText());
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
			
		});
		
		
		MessageConsumer consumer2 = s.createConsumer(d);
		consumer2.setMessageListener(new MessageListener() {

			@Override
			public void onMessage(Message message) {
				TextMessage tm = (TextMessage) message;
				try {
					System.out.println("MessageConsumer2-"+tm.getText());
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
			
		});
		
		MessageProducer producer = s.createProducer(d);
		for(int i=0; i<100; i++) {
			TextMessage msg = s.createTextMessage("msg "+i);
			producer.send(msg);
			System.out.println("MessageProducer-"+msg.getText());
		}
		
		Thread.sleep(20000);
		
		c.close();
		
	}
}
